package com.springboot.example.jar.socket;

import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 作者: guo yao
 * 日期: 2016年02月19日
 * 时间: 下午14:50
 */
public class Demo {

    public static void main(String[] args) throws Exception {
        String ip = "123.56.188.41";//连接服务器的IP
        Integer port = 8017;//连接服务器的端口
        /*InetAddress address = InetAddress.getByName(ip);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);//开启保持活动状态的套接字
        socket.setSoTimeout(10);//设置超时时间
        Boolean result = Send(socket, "2");*/
        System.out.println("result == " + checkPort(ip,port));
    }

    public static Boolean checkPort(String ip,Integer port){
        try{
            InetAddress address = InetAddress.getByName(ip);
            Socket socket = new Socket(address, port);
            socket.setKeepAlive(true);//开启保持活动状态的套接字
            socket.setSoTimeout(10);//设置超时时间
            return Send(socket, "2");
        }catch (Exception se){
            return false;
        }
    }

    /**
     * 发送数据，发送失败返回false,发送成功返回true
     *
     * @param socket
     * @param message
     * @return
     */
    public static Boolean Send(Socket socket, String message) {
        try {
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println(message);
            return true;
        } catch (Exception se) {
            se.printStackTrace();
            return false;
        }
    }
}
